<script lang="ts" setup>
import useAppStore from '@/store/modules/app';
import Tools from '../../utils/tools';
import personal_data from '@/static/img/user/personal_data.png';
import customer_service from '@/static/img/user/customer_service.png';
import setting from '@/static/img/user/setting.png';
import receiving_address from '@/static/img/user/receiving_address.png';
import useModal from '@/hooks/useModal';
import useToast from '@/hooks/useToast';
import UserRequest from '@/request/userRequest';

const store = useAppStore();
const { userInfo } = store.$state;
const { showModal } = useModal();
const { showToast } = useToast();
import { validatePhone } from '@/utils/validate';
import { navigate } from '@/utils/navigate';

interface IState {
  extendCode: string;
  extendShow: boolean;
  agentShow: boolean;
  phone?: number;
  code?: number;
  second: number;
}

const state = reactive<IState>({ extendCode: '', extendShow: false, agentShow: false, second: 0 });

// 处理登出事件
const handlelogOut = () => {
  showModal('确认退出登录吗', {
    showCancel: true,
    success: (res) => {
      if (res.confirm) {
        store.clearLoginStatus();
        showToast('已退出登录');
      }
    },
  });
};

//生成推广码
const openExtendCode = () => {
  UserRequest.CreateExtendCode({ hasLoading: true }).then((res) => {
    state.extendCode = res.data;
    state.extendShow = true;
  });
};

// 业务员认证提交
const handleSalesAuthSub = () => {
  if (!validatePhone(String(state.phone))) {
    showToast('手机号格式错误');
    return;
  }
  if (!state.code) {
    showToast('请填写验证码');
    return;
  }
  UserRequest.SalesmanSubmit({ code: state.code, phone: state.phone, hasLoading: true }).then(() => {
    showToast('提交成功，请等待审核');
    state.agentShow = false;
  });
};

// 获取验证码
const fetchObtainVerificationCode = () => {
  if (!validatePhone(String(state.phone))) {
    showToast('手机号格式错误');
    return;
  }
  UserRequest.FetchSMS({ mobile: state.phone, smsType: 104, hasLoading: true }).then(() => {
    showToast('发送验证码成功', 'success');
    state.second = 60;
    const timer = setInterval(() => {
      state.second--;
      if (state.second <= 0) {
        clearInterval(timer);
        state.second = 0;
      }
    }, 1000);
  });
};
</script>

<template>
  <NotLogged v-if="!store.$state.token" />
  <view v-else>
    <view class="h-[120px] w-screen c-bg" :style="{ paddingTop: `${store.menuInfo.top + store.menuInfo.height}px` }">
      <view class="c-pd flex py-0">
        <van-image round width="80px" height="80px" fit="cover" :src="userInfo.imageUrl" />
        <view class="flex flex-col justify-center pl-[12px]">
          <view class="mb-[10px] text-[22px] fw-bold">
            <text class="mr-12px">{{ userInfo.nickName }}</text>
            <van-tag type="success" v-if="userInfo.detailRole === 2">推广员</van-tag>
            <van-tag type="success" v-if="userInfo.detailRole === 3">业务员</van-tag>
          </view>
          <view class="c-text-color-grey">
            {{ Tools.ProtectingPhoneNumbers(userInfo.phone) }}
          </view>
        </view>
      </view>
    </view>
    <view class="relative top-[-30px] c-pd">
      <view class="box-border w-[100%] flex justify-between overflow-hidden c-br bg-[white]">
        <navigator class="flex flex-1 flex-wrap justify-center p-[8px]" url="/subcontract/person/personalInformation/index">
          <van-image width="30px" height="30px" fit="cover" :src="personal_data" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 个人信息 </view>
        </navigator>
        <navigator class="flex flex-1 flex-wrap justify-center p-[8px]" url="/subcontract/person/shippingAddress/index">
          <van-image width="30px" height="30px" fit="cover" :src="receiving_address" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 收货地址 </view>
        </navigator>
        <navigator @click="Tools.callPhone(userInfo.phone)" class="flex flex-1 flex-wrap justify-center p-[8px]">
          <van-image width="30px" height="30px" fit="cover" :src="customer_service" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 客服 </view>
        </navigator>
        <navigator class="flex flex-1 flex-wrap justify-center p-[8px]" url="/subcontract/person/editProfile/index">
          <van-image width="30px" height="30px" fit="cover" :src="setting" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 设置 </view>
        </navigator>
      </view>
      <view class="grid grid-cols-5 mt-[12px] box-border w-[100%] justify-between gap-0 overflow-hidden c-br bg-[white]">
        <navigator v-if="userInfo.detailRole !== 1" class="flex flex-wrap justify-center py-[8px]" url="/subcontract/person/moneyManagement/index">
          <i class="i-icon-park:funds text-[20px]" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 资金管理 </view>
        </navigator>
        <navigator class="flex flex-wrap justify-center py-[8px]" url="/subcontract/person/pointManagement/index">
          <i class="i-lsicon:order-integral-outline text-[20px]" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 积分管理 </view>
        </navigator>
        <navigator v-if="userInfo.detailRole !== 1" class="flex flex-wrap justify-center py-[8px]" url="/subcontract/person/collectAccount/index">
          <i class="i-mingcute:receive-money-line text-[20px]" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 收款账户 </view>
        </navigator>
        <navigator v-if="(userInfo.detailRole === 2 && userInfo.level) || userInfo.detailRole === 3" class="flex flex-wrap justify-center py-[8px]" url="/subcontract/person/promotionUserList/index">
          <i class="i-fluent:person-star-32-regular text-[20px]" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 推广员 </view>
        </navigator>
        <navigator url=" " v-if="(userInfo.detailRole === 2 && userInfo.level) || userInfo.detailRole === 3" @click="openExtendCode" class="flex flex-wrap justify-center py-[8px]">
          <i class="i-heroicons:qr-code text-[20px]" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 推广码 </view>
        </navigator>
        <navigator v-if="userInfo.detailRole !== 1" class="flex flex-wrap justify-center py-[8px]" url="/subcontract/person/applyCodeManagement/index">
          <i class="i-weui:qr-code-outlined text-[20px]" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 申请码 </view>
        </navigator>
        <navigator v-if="userInfo.detailRole === 3" class="flex flex-wrap justify-center py-[8px]" url="/subcontract/person/areaManagement/index">
          <i class="i-tabler:building-community text-[20px]" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 小区 </view>
        </navigator>
        <navigator url=" " @click="state.agentShow = true" class="flex flex-wrap justify-center py-[8px]">
          <i class="i-fluent:person-accounts-20-regular text-[20px]" />
          <view class="mt-[8px] w-[100%] text-center c-text-12"> 业务员认证 </view>
        </navigator>
      </view>

      <view class="mt-[12px]">
        <van-cell-group inset class="mt-[12px]">
          <van-cell title="紧急联系人" is-link @click="navigate({ url: '/subcontract/person/emergencyContact/index' })">
            <view slot="icon" class="mr-12px flex"> <i class="i-material-symbols:contact-emergency-outline text-[18px]"></i></view>
          </van-cell>
          <van-cell title="社区管理" is-link @click="navigate({ url: `/subcontract/person/webView/index?url=${encodeURIComponent(`https://kics.kanglailab.com/home?userId=${userInfo.userId}&accessToken=${useAppStore().$state.token}`)}` })">
            <view slot="icon" class="mr-12px flex"> <i class="i-iconoir:community text-[18px]"></i></view>
          </van-cell>
          <van-cell is-link @click="handlelogOut">
            <view slot="icon" class="mr-12px flex"> <i class="i-ri:logout-circle-r-line text-[18px]"></i></view>
            <text slot="title" class="color-red"> 退出登录 </text>
          </van-cell>
        </van-cell-group>
      </view>
    </view>
    <van-popup custom-style="height: 40%;width:80%" width :show="state.extendShow" @close="state.extendShow = false">
      <image :src="state.extendCode" class="w-full h-full" />
    </van-popup>
    <van-popup custom-style="height: auto;width:90%" width :show="state.agentShow" @close="state.agentShow = false">
      <view class="w-full h-full bg-white c-br pb-2 box-border">
        <view class="text-align-center c-text-16 c-black py-4 box-border">业务员认证</view>
        <van-cell-group>
          <van-field :value="state.phone" clearable placeholder="请输入手机号" border="false" @change="state.phone = $event.detail">
            <i class="i-clarity:mobile-phone-line c-color w-6 h-6" slot="left-icon"></i>
          </van-field>
          <van-field :value="state.code" center clearable placeholder="请输入短信验证码" @change="state.code = $event.detail" border="false" use-button-slot>
            <i class="i-fluent:shield-task-24-regular c-color w-6 h-6" slot="left-icon"></i>
            <van-button plain slot="button" @click="fetchObtainVerificationCode" :disabled="state.second === 0 ? false : true" size="small" color="#ffc300"> {{ state.second === 0 ? '获取验证码' : state.second + '秒' }} </van-button>
          </van-field>
        </van-cell-group>
        <view class="text-align-center c-text-12 c-red py-3 px-4 box-border">注:您已绑定此手机号，输入新手机号可更换绑定</view>
        <view class="mb-3 px-4 border-box">
          <van-button color="#ffc300" block @click="handleSalesAuthSub" size="small">提交</van-button>
        </view>
      </view>
    </van-popup>
  </view>
  <TabBar active-tab="我的" />
</template>
